package vip.zhaotao.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Zip工具类
 */
public class ZipUtils {

    /**
     * 根据目录生成zip文件
     *
     * @param directory    目录
     * @param outputStream 输出流
     * @throws IOException
     */
    public static void generateZipFileByDirectory(File directory,
                                                  OutputStream outputStream) throws IOException {
        File[] files = directory.listFiles();
        if (ArrayUtils.isNotEmpty(files)) {
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, FileUtils.utf8());
            for (File file : files) {
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                StreamUtils.copy(new FileInputStream(file), zipOutputStream);
            }
            zipOutputStream.flush();
            zipOutputStream.close();
        }
    }
}
